import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { Context } from 'egg';
import * as _ from 'lodash';
import { UserActionLogEntity } from '../entity/userLog';
import { Utils } from '../../../comm/utils';

/**
 * 描述
 */
@Provide()
export class UserActionLogService extends BaseService {
  @Inject()
  ctx: Context;

  @Inject()
  utils: Utils;

  @InjectEntityModel(UserActionLogEntity)
  userActionLogEntity: Repository<UserActionLogEntity>;

  /**
   * 记录
   * @param url URL地址
   * @param params 参数
   * @param userId 用户ID
   */
  async record(context: Context, url, params, userId) {
    const ip = await this.utils.getReqIP(context);
    const sysLog = new UserActionLogEntity();
    sysLog.userId = userId;
    sysLog.ip = typeof ip === 'string' ? ip : ip.join(',');
    const ipAddrArr = [];
    for (const e of sysLog.ip.split(','))
      ipAddrArr.push(await await this.utils.getIpAddr(context, e));
    sysLog.ipAddr = ipAddrArr.join(',');
    sysLog.action = url;
    if (!_.isEmpty(params)) {
      sysLog.params = JSON.stringify(params);
    }
    console.log('user_action_log------用户行为--log------->', sysLog);

    await this.userActionLogEntity.insert(sysLog);
  }

  /**
   * 获取用户的最新ip属地
   * @param userId
   */
  async getUserIpAddr(userId: any) {
    const data = await this.userActionLogEntity
      .createQueryBuilder('a')
      .select('a.ip_addr')
      .where({ userId })
      .orderBy('a.updateTime', 'DESC')
      .getRawOne();
    return data ? data.ip_addr : null;
  }
}
